import { createSlice } from '@reduxjs/toolkit';

const networkStatusSlice = createSlice({
	name: 'networkStatus',
	initialState: {
		amsStatus: '', // 本地ams网络连接状态['connected','reconnect_failed','reconnecting', 'offline', 'online']
		ccsStatus: '', // 本地ccs网络连接状态['connected','reconnect_failed','reconnecting', 'offline', 'online']
		remoteStatus: [] // // ccs远端访客和坐席网络连接状态 [{id:id, status:'connected'|'reconnect_failed'|'reconnecting'}]
	},

	reducers: {
		setLocalAmsStatus(state, action) {
			return Object.assign(state, { amsStatus: action.payload });
		},
		setLocalCcsStatus(state, action) {
			return Object.assign(state, { ccsStatus: action.payload });
		},
		setRemoteStatus(state, action) {
			const { id, status } = action.payload;
			let cloneStatus: any[] = [...state.remoteStatus];
			const items = state.remoteStatus.filter(item => (item as any).id === id);
			if (items && items.length > 0) {
				cloneStatus.map(item => {
					if ((item as any).id === id) {
						(item as any).status = status;
					}
				});
			} else {
				let data: any = { id: id, status: status };
				cloneStatus.push(data);
			}
			return Object.assign(state, { remoteStatus: cloneStatus });
		},
		removeRemoteStatus(state, action) {
			const { id } = action.payload;
			let cloneStatus: any[] = [...state.remoteStatus];
			const index = state.remoteStatus.findIndex(item => (item as any).id === id);
			if (index >= 0) {
				cloneStatus.splice(index, 1);
			}
			return Object.assign(state, { remoteStatus: cloneStatus });
		},
		clearNetworkStatusData(state) {
			return {
				amsStatus: state.amsStatus,
				ccsStatus: '',
				remoteStatus: []
			};
		},
		resetNetworkStatus() {
			return {
				amsStatus: '',
				ccsStatus: '',
				remoteStatus: []
			};
		}
	}
});

export const { setLocalCcsStatus, setRemoteStatus, setLocalAmsStatus, removeRemoteStatus, clearNetworkStatusData, resetNetworkStatus } = networkStatusSlice.actions;
export default networkStatusSlice.reducer;
